﻿using System;
using System.Data;
using System.Reflection;
using System.Text.RegularExpressions;
using WFC.BL.Interfaces.Utilities;

namespace WFC.BL.Utilities
{

    public class UtilityService : IUtilityService
    {

        #region IUtilityManager Members

        public string HtmlOptimizer(string html)
        {
            if (String.IsNullOrEmpty(html))
                throw new ArgumentNullException("html");

            html = new Regex(@">(?! )\s+", RegexOptions.Compiled).Replace(html, ">");
            html = new Regex(@"([\n\s])+?(?<= {2,})<", RegexOptions.Compiled).Replace(html, "<");

            return html.Trim();
        }

        public T MapDataRowToEntity<T>(DataRow dataRow) where T : new()
        {
            if (dataRow == null)
                throw new ArgumentNullException("dataRow");

            var entityType = typeof(T);
            var properties = entityType.GetProperties();

            T entity = new T();
            foreach (PropertyInfo info in properties)
            {
                string colName = info.Name;
                if (!(dataRow[colName] is DBNull))
                    info.SetValue(entity, dataRow[colName], null);
            }

            return entity;
        }

        #endregion

    }

}
